#include "napi/native_api.h"
#include <multimedia/image_framework/image/pixelmap_native.h>
#include <multimedia/image_framework/image/image_source_native.h>
#include "RcpRequest.cpp"
#include "ImageMerge.cpp"
#include "ffrt/ffrt.h"
#include "hilog/log.h"

using namespace std;


// 测试用，测试请求是否能够成功
napi_value TestGetImageFromNapi(napi_env env, napi_callback_info info) {
    const char *url = "http://p1-tt.bytecdn.cn/origin/16ab000fd406f6562385";

    OH_PixelmapNative *pixelMap = nullptr;
    ffrt::submit([url, &pixelMap] { GetPixelMapFromNet(url, &pixelMap); });
    ffrt::wait();
    napi_value result = nullptr;
    OH_PixelmapNative_ConvertPixelmapNativeToNapi(env, pixelMap, &result);
    return result;
}

napi_value MergePixelMaps(napi_env env, napi_callback_info info) {
    clock_t start,end;
    start = clock();
    OH_LOG_Print(LOG_APP, LOG_INFO, LOG_DOMAIN, "CHEN", "[MergePixel] StartTime = %{public}d", start);
    const char *verifyUrl = "http://p1-tt.bytecdn.cn/origin/16ab000fd406f6562385";
    const char *avatarUrl =
        "https://fastly.picsum.photos/id/609/200/200.jpg?hmac=Fe1MOOyr8RJSloodBDzO2oMGF2NvnJVhuoGNDTC5clU";
    const char *decorationUrl =
        "https://pic.rmb.bdstatic.com/bjh/news/8bfa1a40e0194d787e7f98f2115f6b97.png";

    OH_PixelmapNative *decoration = nullptr;
    OH_PixelmapNative *avatar = nullptr;
    OH_PixelmapNative *verify = nullptr;
    
    ffrt::submit([decorationUrl, &decoration] { GetPixelMapFromNet(decorationUrl, &decoration); });
    ffrt::submit([avatarUrl, &avatar] { GetPixelMapFromNet(avatarUrl, &avatar); });
    ffrt::submit([verifyUrl, &verify] { GetPixelMapFromNet(verifyUrl, &verify); });
    // 多个任务后，需要机械能wait，等待请求同步
    ffrt::wait();
    OH_PixelmapNative *mergedPixel = nullptr;
    MergeAvatar(decoration, avatar, verify, &mergedPixel);

    napi_value result = nullptr;
    OH_PixelmapNative_ConvertPixelmapNativeToNapi(env, mergedPixel, &result);
    
    end = clock();
    
    OH_LOG_Print(LOG_APP, LOG_INFO, LOG_DOMAIN, "CHEN", "[MergePixel] EndTime = %{public}d", end);
    OH_LOG_Print(LOG_APP, LOG_INFO, LOG_DOMAIN, "CHEN", "[MergePixel] totalTime = %{public}f", (double )(end - start)/CLOCKS_PER_SEC);
    
    return result;
}


EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports) {
    napi_property_descriptor desc[] = {
        {"mergePixelMaps", nullptr, MergePixelMaps, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"testGetImageFromNapi", nullptr, TestGetImageFromNapi, nullptr, nullptr, nullptr, napi_default, nullptr}};

    napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
    return exports;
}
EXTERN_C_END

static napi_module demoModule = {
    .nm_version = 1,
    .nm_flags = 0,
    .nm_filename = nullptr,
    .nm_register_func = Init,
    .nm_modname = "entry",
    .nm_priv = ((void *)0),
    .reserved = {0},
};

extern "C" __attribute__((constructor)) void RegisterEntryModule(void) { napi_module_register(&demoModule); }
